﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MovieModels;
using System.IO;
using System.Net;
using MKDataBase.Contracts;
using Manas.Core.Extensions;

namespace MK_Movie_Manager.EditMovieDeails
{
    public partial class MovieDetailsEditComponent : UserControl
    {
        private IMDBMovie movieDetails;
        private int movieManagerID;
        private IDBProvider MovieDB;
        public MovieDetailsEditComponent()
        {
            this.MovieDB = MMSettings.CurrentDBInstance;
            InitializeComponent();
        }

        public void UpDateMovieDetails(IMDBMovie movieDetails, int movieManagerID)
        {
            this.movieDetails = movieDetails;
            this.movieManagerID = movieManagerID;
            this.pbMoviePoster.Image = null;
            InitializeMovie();
        }

        private void InitializeMovie()
        {
            this.txtMovieID.Text = this.movieDetails.MovieId;
            this.txtMovieTitle.Text = this.movieDetails.MovieTitle;
            this.txtIMDBUrl.Text = this.movieDetails.ImdbUrl;
            this.txtReleaseDate.Text = this.movieDetails.ReleaseDate;
            this.txtMovieRating.Text = this.movieDetails.Rating;
            this.txtTagLine.Text = WebHelper.HtmlDecode(this.movieDetails.TagLine);
            this.rtbStoryline.Text = WebHelper.HtmlDecode(this.movieDetails.StoryLine);
            this.pbMoviePoster.ImageLocation = this.movieDetails.PosterUrl;
            this.txtGenre.Text = this.movieDetails.Genres.Aggregate((f, l) => f + '#' + l);
        }

        private void btnUpdateDetails_Click(object sender, EventArgs e)
        {
            try
            {
                MovieDetailsDataRow movieDetails = new MovieDetailsDataRow()
                {
                    ID = this.movieManagerID,
                    IMDBId = this.txtMovieID.Text,
                    IMDBUrl = this.txtIMDBUrl.Text,
                    Rating = Convert.ToSingle(this.txtMovieRating.Text.IsNullOrWhitespace() ? "0" : this.txtMovieRating.Text),
                    Releasedate = Convert.ToDateTime(this.txtReleaseDate.Text),
                    Genre = this.txtGenre.Text,
                    StoryLine = this.rtbStoryline.Text,
                    TagLine = this.txtTagLine.Text,
                    Title = this.txtMovieTitle.Text,
                    MovieImage = RetriveImage(this.pbMoviePoster.ImageLocation)
                };
                DBStatus status = MovieDB.AddMovieDetails(movieDetails);
                if (status.Equals(DBStatus.RowExists))
                    MessageBox.Show("Movie already exists.");
                else if (status.Equals(DBStatus.Success))
                    MessageBox.Show("Movie details sucesssfully added");
                this.btnUpdateDetails.Enabled = false;
            }
            catch
            {
                MessageBox.Show("Unknown Error ccured. ReInstall application.");
            }
        }

        private byte[] RetriveImage(string url)
        {

            byte[] b;//=new byte[500000];
            if (!string.IsNullOrWhiteSpace(url))
            {
                if (!IsLocalPath(url))
                {
                    HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
                    WebResponse myResp = myReq.GetResponse();

                    Stream stream = myResp.GetResponseStream();
                    int i;
                    using (BinaryReader br = new BinaryReader(stream))
                    {
                        i = (int)(myResp.ContentLength);
                        b = br.ReadBytes(i);
                        br.Close();
                    }
                    myResp.Close();
                    return b;
                }
                else {
                    using (FileStream file = new FileStream(url, FileMode.Open, FileAccess.Read))
                    {
                        b = new byte[file.Length];
                        file.Read(b, 0, (int)file.Length);                        
                    }
                    return b;
                }
            }
            return new byte[0];

        }

        public void SetImage(byte[] imgStream)
        {
            MemoryStream imgstr = new MemoryStream(imgStream);

            try
            {
                if (imgstr == null || imgStream.Count() == 0)
                    this.pbMoviePoster.Image = null;
                else
                    this.pbMoviePoster.Image = Image.FromStream(imgstr);
            }
            catch { }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string imgPath;
            if (TextInputDialog.ShowCustomDialog(out imgPath).Equals(DialogResult.OK))
            {
                if (!imgPath.IsNullOrWhitespace())
                {
                    this.pbMoviePoster.ImageLocation = imgPath;
                    //RetriveImage(imgPath);
                }
            }
        }

        private static bool IsLocalPath(string p)
        {
            if (p.StartsWith("http:\\"))
            {
                return false;
            }

            return new Uri(p).IsFile;
        }

    }
}
